#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import asyncio
from playwright.async_api import async_playwright

from app.services.mcp_server.mcp_client import MCPClient

host = '127.0.0.1'


async def attach_to_browser(cdp_endpoint=None):
    """通过 CDP 接管已启动的浏览器，并导航到知乎首页"""
    if cdp_endpoint is None:
        cdp_endpoint = f'http://{host}:9222'
    # 确保cdp_endpoint是完整的HTTP URL格式
    if not cdp_endpoint.startswith('http://') and not cdp_endpoint.startswith('https://'):
        cdp_endpoint = f'http://{cdp_endpoint}'

    async with async_playwright() as p:
        print(f"[attach] 正在连接到CDP端点: {cdp_endpoint}")
        browser = await p.chromium.connect_over_cdp(cdp_endpoint)

        context = browser.contexts[0] if browser.contexts else await browser.new_context()
        page = context.pages[0] if context.pages else await context.new_page()

        print(f"[attach] 当前页面标题: {await page.title()}")
        print(f"[attach] 当前 URL: {page.url}")

        await page.goto("https://toolsdar.cn/", wait_until="domcontentloaded")

        print(f"[attach] 当前页面标题: {await page.title()}")
        print(f"[attach] 当前 URL: {page.url}")
        
        # 返回浏览器和页面对象，而不是退出程序
        return browser, page


async def demo_mcp_browser():
    """使用 MCP 客户端打开百度、知乎并截图"""
    http_url = f"http://{host}:8931/sse"
    client = MCPClient(http_url)

    async with client:
        tools = await client.list_tools()
        await client.call_tool("browser_navigate", {"url": "https://www.baidu.com"})
        await asyncio.sleep(3)

        await client.call_tool("browser_navigate", {"url": "https://www.zhihu.com"})
        screenshot = await client.call_tool("browser_snapshot", {})
        print("[mcp_server] 截图结果:", str(screenshot)[:200])

        await asyncio.sleep(3)  # 留时间人工查看

        # 接管浏览器继续操作，但不退出程序
        browser, page = await attach_to_browser()
        print("[attach] 浏览器接管完成，测试结束")


if __name__ == "__main__":
    asyncio.run(demo_mcp_browser())
